import backtrader as bt
from tools import *
import json


class StrategyExt(bt.Strategy):
    params = {}

    cash = 0

    # value = 0

    def __init__(self, target=None):
        return

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            return
        money = order.executed.price * order.executed.size
        # if order.isbuy():
        # 	self.cash += money
        # elif order.issell():
        # 	self.value += -money
        operate = 'buy' if order.isbuy() else 'sell'
        self.cash += money
        self.log(
            operate + ', price: %.2f, cost: %.2f, Comm %.2f' %
            (order.executed.price, money, order.executed.comm), 10)

    def next(self):
        self.log('next price:%.2f' % (self.dataclose[0]))

    def log(self, txt, level=0):
        dt = self.datas[0].datetime.date(0)
        info = '%s, %s' % (dt.isoformat(), txt)
        tool.log(info, level)

    def stop(self):
        # code = tool.code
        # cash = self.broker.getcash()
        # value = self.broker.getvalue()
        # profit = value - cash
        # profitRate = round(profit / cash, 3)
        # params = json.dumps(self.params.__dict__)
        # res = {'cash': cash, 'value': value, 'profit_rate': profitRate,
        # 	   'params': params, 'code': code, 'strategy': self.__class__.__name__,
        # 	   'profit_type': 'input_money_base'}
        # self.log('stop,  input:{0}, output:{1}'.format(self.cash, self.value), 30)
        # self.log(json.dumps(res), 30)
        self.log(self.cash, 30)
        return None
